package com.example.home.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.home.api.ApiService;
import com.example.home.interfaces.ResponseCallback;
import com.example.home.viewmodel.Login.LoginData;
import com.example.home.viewmodel.Login.UserInfo;
import com.example.home.viewmodel.ResponseData;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    //全局变量
    EditText oUser;
    EditText oPwd;

    UserInfo userInfo;

    Boolean login_status = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        oUser = findViewById(R.id.username);
        oPwd = findViewById(R.id.password);
        Button oLogin = findViewById(R.id.login);

        oLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String name = oUser.getText().toString();
        String pwd = oPwd.getText().toString();
        Map<String, String> params = new HashMap<>();
        params.put("username", name);
        params.put("password", pwd);


        ApiService.Login(v, params, new ResponseCallback<ResponseData<LoginData>>() {
            @Override
            public void onSuccess(ResponseData<LoginData> result) {
                String msg = result.getErrmsg();
                if(msg.equals("成功")) {
                    userInfo = result.getData().getUserInfo();
                    Toast.makeText(v.getContext(), "登录成功", Toast.LENGTH_SHORT).show();
                    SharedPreferences sp = getSharedPreferences("user_info", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username", userInfo.getNickName()); // 存储字符串
                    editor.putString("avatar", userInfo.getAvatarUrl());
                    editor.putString("token", result.getData().getToken());
                    editor.apply(); // 异步提交（推荐，不阻塞UI）
                    Intent intent = new Intent(v.getContext(), MainActivity.class);
                    intent.putExtra("login_status",true);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(v.getContext(), "登录失败", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}